#coding=utf-8
__author__ = 'jy@cjlu.edu.cn'
from basehandler import basehandler
from SysCommon.exceloperator import ExcelOperator
from iLibP.loger import LogError
import web
from SysCommon.tools import *
from models.s_fun import *
import json
from config import global_lookup

def DataFilter(i):
    obj=bll_s_fun()
    i.recs=[]
    i.head=i.get("head","10")
    strwhere=" id>0 "
    #补充其他查询条件
    if i.head:
        strwhere+=" and funno like '"+i.head+"%' order by funno asc"
    recs=obj.GetRowsByStrWhere(strwhere)
    recs=recs.list()
    for r in recs:
        t=storage()
        t.id=r.id
        l=(len(r.funno)-2)*2
        t.funno=r.funno
        t.funname="".ljust(l,'-')+str(r.funname)
        i.recs.append(t)
    return i

class Ajax(basehandler):
    def post(self):
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        i=self.input()
        obj=bll_s_fun()
        if i.act=="del":
            if i.id:
                obj.DelRowById(i.id)
                return json.dumps({"result":"OK"})
        if i.act=="add":
            try:
                i.id=0
                obj.Save(i)
                obj.refreshPowers()
                self.write(json.dumps({"result":"OK"}))
            except Exception,ex:
                print ex
                self.write(json.dumps({"result":"NOOK"}))
        if i.act=="edit":
            obj.Save(i)
            from server import refreshPowers
            refreshPowers()
            self.write(json.dumps({"result":"OK"}))
class List(basehandler):
    """
    用于处理列表页面或默认显示页面
    对于数据的删除或简单AJAX的操作也放置在此类中，
    可放置于POST函数内
    """
    def get(self):
        def _list(i):
            if i.act=="list":
                t=global_lookup.get_template("f00/T/fun_list.html")
                i=DataFilter(i)
                return t.render(i=i)
        def _update(i):
            if i.act=="update":
                obj=bll_s_fun()
                t=global_lookup.get_template("f00/T/fun_update.html")
                if i.get("id",None):
                    i.rec=obj.GetRowById(i.id)
                return t.render(i=i)
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        i.act=i.get('act','list')
        if ["list","update"].__contains__(i.act):
            self.write(apply(eval("_"+i.act),(),{"i":i}))
        else:
            self.write(ShowErrorAndGoBack("参数错误！"))
    def POST(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        self.get()

class Import(basehandler):
    def get(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        #请修改路径
        t=global_lookup.get_template("f00/T/fun_import.html")
        self.write(t.render())
    def post(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        optobj=bll_s_fun()
        #1.导入数据时只做更新操作，特别注意不能删除数据
        dbt=optobj.Transaction()
        eo=ExcelOperator()                          #file控件名要为excel
        f=eo.uploadFile()
        result=eo.parseExcel(f)
        importresult=[]
        try:
            for d in result.data:
                #查找部分数据
                try:
                    #修改查询条件
                    strwhere="funno='"+d.funno+"'"
                    rec=optobj.GetRowByStrWhere(strwhere)
                    if rec:#找到更新
                        d=CopyData(rec,d)
                        #补充需要更新的列名
                        optobj.Save(d)
                        d.importstatus=u"【成功】更新"
                    else:#找不到则写入
                        d.id=0
                        optobj.Save(d)
                        d.importstatus=u"【成功】写入"
                except Exception,ex1:
                    print ex1
                    d.importstatus=u"【失败】数据异常"
                importresult.append(d)
            optobj.Commit(dbt)
            t=global_lookup.get_template("f00/T/fun_importresult.html")
            self.write(t.render(datas=importresult))
        except Exception,ex:
            msg=u"iLib执行Save函数出错,[具体信息]:"+str(ex)
            LogError(msg)
            optobj.RollBack(dbt)
            raise Exception,msg
class Export(basehandler):
    """
    用于将数据导出向EXCEL
    """
    def get(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        from SysCommon.exceloperator import ExcelOperator
        excelobj=ExcelOperator()
        wb,ws=excelobj.openExistExcel(TP_PATH+"/static/T/fun.xls")
        start_row=3
        #1.获取数据
        bjobj=bll_s_fun()
        datas=bjobj.GetRowsByDbWhere()
        #2.组合excel
        for d in datas:
            ws.write(start_row,0,d.funno)
            ws.write(start_row,1,d.funname)
            ws.write(start_row,2,d.funcatalog)
            ws.write(start_row,3,d.funclass)
            ws.write(start_row,4,d.displayname)
#            ws.write(start_row,5,d.templatefile)
            start_row+=1
            #3.输出excel
        nfilename="/static/tmpfiles/fun.xls"
        wb.save(TP_PATH+nfilename)
        self.redirect(nfilename)